<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import NewShopAuthService from '../services/NewShopAuthService.js'
import NewShopCartService from '../services/NewShopCartService.js'

const router = useRouter()
const cartItems = ref([])
const isLoading = ref(false)
const errorMessage = ref('')

// 检查登录状态
onMounted(() => {
  if (!NewShopAuthService.isLoggedIn()) {
    // 如果未登录，跳转到登录页面
    router.push('/new-shop-login')
    return
  }
  
  loadCartItems()
})

// 加载购物车商品
const loadCartItems = () => {
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    // 模拟API调用延迟
    setTimeout(() => {
      cartItems.value = NewShopCartService.getCart()
      isLoading.value = false
    }, 300)
  } catch (error) {
    errorMessage.value = '加载购物车失败'
    console.error('加载购物车错误:', error)
    isLoading.value = false
  }
}

// 更新商品数量
const updateQuantity = async (item, newQuantity) => {
  if (newQuantity < 1) newQuantity = 1
  
  try {
    await NewShopCartService.updateQuantity(
      item.productId,
      item.color,
      item.size,
      newQuantity
    )
    
    // 更新本地购物车数据
    const index = cartItems.value.findIndex(
      cartItem => 
        cartItem.productId === item.productId && 
        cartItem.color === item.color && 
        cartItem.size === item.size
    )
    
    if (index >= 0) {
      if (newQuantity <= 0) {
        cartItems.value.splice(index, 1)
      } else {
        cartItems.value[index].quantity = newQuantity
      }
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    alert('更新数量失败，请重试')
  }
}

// 从购物车移除商品
const removeFromCart = async (item) => {
  try {
    await NewShopCartService.removeFromCart(
      item.productId,
      item.color,
      item.size
    )
    
    // 更新本地购物车数据
    const index = cartItems.value.findIndex(
      cartItem => 
        cartItem.productId === item.productId && 
        cartItem.color === item.color && 
        cartItem.size === item.size
    )
    
    if (index >= 0) {
      cartItems.value.splice(index, 1)
    }
  } catch (error) {
    console.error('移除商品失败:', error)
    alert('移除商品失败，请重试')
  }
}

// 清空购物车
const clearCart = async () => {
  if (confirm('确定要清空购物车吗？')) {
    try {
      await NewShopCartService.clearCart()
      cartItems.value = []
    } catch (error) {
      console.error('清空购物车失败:', error)
      alert('清空购物车失败，请重试')
    }
  }
}

// 继续购物
const continueShopping = () => {
  router.push('/new-shop')
}

// 去结算
const goToCheckout = () => {
  if (cartItems.value.length === 0) {
    alert('购物车为空，请先添加商品')
    return
  }
  
  router.push('/new-shop/checkout')
}

// 查看商品详情
const viewProductDetail = (productId) => {
  router.push(`/new-shop/product/${productId}`)
}

// 计算购物车总价
const cartTotalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
})

// 计算购物车商品总数
const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})
</script>

<template>
  <div class="new-shop-cart-container">
    <!-- 导航栏 -->
    <nav class="new-shop-nav">
      <div class="nav-logo">
        <svg viewBox="0 0 24 24" width="24" height="24" stroke="#2196F3" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
          <circle cx="9" cy="21" r="1"></circle>
          <circle cx="20" cy="21" r="1"></circle>
          <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
        </svg>
        <span>NewShop</span>
      </div>
    </nav>
    
    <!-- 主要内容 -->
    <main class="new-shop-cart-main">
      <div class="cart-header">
        <h1>购物车</h1>
        <p>共 {{ cartItemCount }} 件商品</p>
      </div>
      
      <div v-if="isLoading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="errorMessage" class="error-state">
        <p>{{ errorMessage }}</p>
        <button class="retry-button" @click="loadCartItems">重试</button>
      </div>
      
      <div v-else-if="cartItems.length === 0" class="empty-cart-state">
        <div class="empty-cart-icon">
          <svg viewBox="0 0 24 24" width="64" height="64" stroke="#ddd" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="9" cy="21" r="1"></circle>
            <circle cx="20" cy="21" r="1"></circle>
            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
          </svg>
        </div>
        <h3>购物车还是空的</h3>
        <p>快去添加心仪的商品吧</p>
        <button class="primary-button" @click="continueShopping">继续购物</button>
      </div>
      
      <div v-else class="cart-content">
        <!-- 购物车商品列表 -->
        <div class="cart-items-section">
          <div class="cart-items-header">
            <div class="header-item header-checkbox">
              <input type="checkbox" class="select-all-checkbox" checked />
              <span>全选</span>
            </div>
            <div class="header-item header-product">商品信息</div>
            <div class="header-item header-price">单价</div>
            <div class="header-item header-quantity">数量</div>
            <div class="header-item header-subtotal">小计</div>
            <div class="header-item header-action">操作</div>
          </div>
          
          <div class="cart-items-list">
            <div 
              v-for="(item, index) in cartItems" 
              :key="`${item.productId}-${item.color}-${item.size}`"
              class="cart-item"
            >
              <div class="cart-item-cell cart-item-checkbox">
                <input type="checkbox" checked />
              </div>
              <div class="cart-item-cell cart-item-product">
                <div class="product-image" @click="viewProductDetail(item.productId)">
                  <img :src="item.image" :alt="item.productName" />
                </div>
                <div class="product-info">
                  <h4 class="product-name" @click="viewProductDetail(item.productId)">{{ item.productName }}</h4>
                  <div class="product-options">
                    <span>颜色：{{ item.color }}</span>
                    <span>尺寸：{{ item.size }}</span>
                  </div>
                </div>
              </div>
              <div class="cart-item-cell cart-item-price">¥{{ item.price }}</div>
              <div class="cart-item-cell cart-item-quantity">
                <div class="quantity-selector">
                  <button 
                    class="quantity-button minus"
                    @click="updateQuantity(item, item.quantity - 1)"
                    :disabled="item.quantity <= 1"
                  >
                    -
                  </button>
                  <span class="quantity-value">{{ item.quantity }}</span>
                  <button 
                    class="quantity-button plus"
                    @click="updateQuantity(item, item.quantity + 1)"
                  >
                    +
                  </button>
                </div>
              </div>
              <div class="cart-item-cell cart-item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              <div class="cart-item-cell cart-item-action">
                <button class="remove-button" @click="removeFromCart(item)">
                  <svg viewBox="0 0 24 24" width="16" height="16" stroke="#666" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                  </svg>
                </button>
              </div>
            </div>
          </div>
          
          <div class="cart-actions">
            <button class="clear-cart-button" @click="clearCart">
              <svg viewBox="0 0 24 24" width="16" height="16" stroke="#666" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="3 6 5 6 21 6"></polyline>
                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                <line x1="10" y1="11" x2="10" y2="17"></line>
                <line x1="14" y1="11" x2="14" y2="17"></line>
              </svg>
              清空购物车
            </button>
            <button class="continue-shopping-button" @click="continueShopping">
              继续购物
            </button>
          </div>
        </div>
        
        <!-- 购物车结算区域 -->
        <div class="cart-checkout-section">
          <div class="checkout-summary">
            <div class="summary-row">
              <span>商品总价：</span>
              <span class="summary-value">¥{{ cartTotalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-row">
              <span>优惠：</span>
              <span class="summary-value discount">-¥0.00</span>
            </div>
            <div class="summary-row">
              <span>运费：</span>
              <span class="summary-value">¥0.00</span>
            </div>
            <div class="summary-row total">
              <span>实付款：</span>
              <span class="summary-value total-price">¥{{ cartTotalPrice.toFixed(2) }}</span>
            </div>
          </div>
          
          <div class="checkout-actions">
            <button class="checkout-button" @click="goToCheckout">
              去结算 ({{ cartItemCount }})
            </button>
          </div>
        </div>
      </div>
    </main>
    
    <!-- 页脚 -->
    <footer class="new-shop-footer">
      <div class="footer-bottom">
        <p>© 2024 NewShop. 保留所有权利。</p>
      </div>
    </footer>
  </div>
</template>

<style scoped>
.new-shop-cart-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 导航栏样式 */
.new-shop-nav {
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 15px 30px;
  display: flex;
  align-items: center;
}

.nav-logo {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
  color: #2196F3;
}

.nav-logo svg {
  margin-right: 10px;
}

/* 主要内容样式 */
.new-shop-cart-main {
  flex: 1;
  padding: 30px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.cart-header h1 {
  margin: 0;
  font-size: 32px;
  color: #333;
}

.cart-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #2196F3;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #f44336;
  font-size: 18px;
}

.retry-button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
}

.empty-cart-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  text-align: center;
}

.empty-cart-icon {
  margin-bottom: 20px;
}

.empty-cart-state h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.empty-cart-state p {
  margin: 0 0 30px 0;
  color: #666;
  font-size: 16px;
}

.primary-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.primary-button:hover {
  background-color: #1976D2;
  transform: translateY(-1px);
}

/* 购物车内容区域 */
.cart-content {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 30px;
  align-start;
}

/* 购物车商品列表样式 */
.cart-items-section {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cart-items-header {
  display: grid;
  grid-template-columns: 100px 1fr 120px 180px 120px 80px;
  background-color: #f8f9fa;
  padding: 20px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #eee;
}

.header-item {
  display: flex;
  align-items: center;
}

.header-checkbox {
  gap: 10px;
}

.cart-items-list {
  max-height: 600px;
  overflow-y: auto;
}

.cart-item {
  display: grid;
  grid-template-columns: 100px 1fr 120px 180px 120px 80px;
  padding: 20px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s ease;
}

.cart-item:hover {
  background-color: #f8f9fa;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item-cell {
  display: flex;
  align-items: center;
}

.cart-item-checkbox {
  justify-content: center;
}

.cart-item-product {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}

.product-options {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
  color: #666;
}

.cart-item-price {
  font-size: 16px;
  color: #333;
  justify-content: center;
}

.quantity-selector {
  display: flex;
  align-items: center;
  width: 120px;
  justify-content: center;
}

.quantity-button {
  width: 36px;
  height: 36px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.quantity-button:hover:not(:disabled) {
  background-color: #f5f5f5;
}

.quantity-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-button:first-child {
  border-radius: 6px 0 0 6px;
}

.quantity-button:last-child {
  border-radius: 0 6px 6px 0;
}

.quantity-value {
  flex: 1;
  text-align: center;
  padding: 8px 0;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  font-size: 16px;
}

.cart-item-subtotal {
  font-size: 18px;
  font-weight: 600;
  color: #2196F3;
  justify-content: center;
}

.cart-item-action {
  justify-content: center;
}

.remove-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.remove-button:hover {
  background-color: #ffebee;
}

.remove-button:hover svg {
  stroke: #f44336;
}

/* 购物车操作样式 */
.cart-actions {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background-color: white;
  border-top: 1px solid #eee;
}

.clear-cart-button {
  display: flex;
  align-items: center;
  gap: 5px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  font-size: 16px;
  transition: color 0.3s ease;
}

.clear-cart-button:hover {
  color: #f44336;
}

.continue-shopping-button {
  background-color: #f5f5f5;
  color: #333;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.continue-shopping-button:hover {
  background-color: #e0e0e0;
}

/* 购物车结算区域样式 */
.cart-checkout-section {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 100px;
}

.checkout-summary {
  margin-bottom: 30px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
}

.summary-row span:first-child {
  color: #666;
}

.summary-value {
  color: #333;
  font-weight: 600;
}

.summary-value.discount {
  color: #f44336;
}

.summary-row.total {
  padding-top: 20px;
  border-top: 1px solid #eee;
  margin-top: 20px;
}

.total-price {
  font-size: 24px;
  color: #2196F3;
}

.checkout-actions {
  display: flex;
  justify-content: center;
}

.checkout-button {
  width: 100%;
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 15px;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.checkout-button:hover {
  background-color: #1976D2;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.checkout-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 页脚样式 */
.new-shop-footer {
  background-color: #333;
  color: white;
  padding: 30px;
  margin-top: 60px;
}

.footer-bottom {
  text-align: center;
  font-size: 14px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .cart-content {
    grid-template-columns: 1fr;
  }
  
  .cart-checkout-section {
    position: static;
  }
}

@media (max-width: 768px) {
  .cart-items-header {
    display: none;
  }
  
  .cart-item {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto;
    gap: 15px;
    padding: 15px;
  }
  
  .cart-item-cell {
    justify-content: space-between;
  }
  
  .cart-item-product {
    justify-content: flex-start;
  }
  
  .cart-item-checkbox {
    justify-content: flex-start;
    order: -1;
  }
  
  .cart-actions {
    flex-direction: column;
    gap: 15px;
  }
}
</style>